/*
 * Conn.cpp
 *
 *   Created on: 2010-3-24     
 *  Description: 
 *    Copyright: 2010 @ ICT Li Heyuan
 */

#include "../../include/server/Server.h"
#include "../../include/conn/Conn.h"
#include "../../include/json_cpp/value.h"
#include "../../include/util/JsonRpcException.h"
using Json::Value;

#include <stdexcept>
using std::runtime_error;

bool Conn::callMethod(string &error)
{
	try
	{
		//先找有没有这个方法
		string method_str = _jsonReq["method"].asString();

		//检查method不能为空
		if (method_str.empty())
		{
			throw JsonRpcException("Method can't be null.");
		}

		RpcMethod *method = _server->findMethod(method_str);

		//检查method是否没有找到
		if (method == NULL)
		{
			throw JsonRpcException("Method " + method_str
					+ " not found on rpcServer.");
		}//end if method==NULL
		else
		{
			return method->execute(_jsonReq, _jsonResp, _addr, error);
		}//end if method!=NULL
	} catch (runtime_error &err)
	{
		error = err.what();
		_jsonResp[Const::ID] = _jsonReq["id"];
		_jsonResp[Const::ERROR] = error;
		_jsonResp[Const::RESULT] = Value::null;

		return false;
	} catch (JsonRpcException &exception)
	{
		error = exception.what();
		_jsonResp[Const::ID] = _jsonReq["id"];
		_jsonResp[Const::ERROR] = error;
		_jsonResp[Const::RESULT] = Value::null;

		return false;
	} catch (...)
	{
		error = "unknown error.";
		_jsonResp[Const::ID] = _jsonReq["id"];
		_jsonResp[Const::ERROR] = error;
		_jsonResp[Const::RESULT] = Value::null;

		return false;
	}
}
